import { CaretDownOutlined, CaretRightOutlined, PlusOutlined } from '@ant-design/icons';
import { useSize } from 'ahooks';
import {
  Typography,
  Button,
  Dropdown,
  MenuProps,
  Input,
  Select,
  message,
  TreeSelect,
  List,
} from 'antd';
import { memo, useEffect, useRef, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import datasetService from '@/api/services/datasetService';
import { MAX_NAME_LENGTH } from '@/common';
import { UserRoleEnum } from '@/common/app/constants';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import PersonnelModal from '@/components/personnel-modal/personnel-modal';
import TipDesc from '@/components/tipDesc/tipDesc';
import useWindowWidth from '@/hooks/event/use-window-width';
import usePermission from '@/hooks/event/usePermission';
import { useRouter, useParams } from '@/router/hooks';
import { useDatasetStore } from '@/store/datasetStore';
import { useUserInfo } from '@/store/userStore';
import { getNodeParentType, processData, treeToPlainList } from '@/utils/tree';

import { DatasetsContext } from '../../context';
import BreadCrumb from '../BreadCrumb';
import DatasetsTreeList from '../DatasetsTreeList';
import MoveToModal from '../MoveToModal';
import '../../styles/datasetlist.scss';
import UpdateDatasetModal from '../UpdateDatasetModal';

import OvertimeModal from './OvertimeModal';
import UpdateNameModal from './UpdateNameModal';

import type { TreeSelectProps } from 'antd';

import { useOrchestrationStore } from '@/store/orchestrationStore';
import useModal from '@/hooks/use-modal/useModal';
import { TreeData } from '@/types/dataset';

import { getIsEditPermission } from '../../utils/status';

const { Text } = Typography;

interface Props {
  dataLoading: boolean;
  onRenameClicked?: (name: string) => void;
  onDeleteClicked?: (key: string, type: string) => void;
  onRewareHousingClicked?: (key: string, type: string) => void;
  onCreateCicked?: (type: string) => void;
  onCloseCicked?: () => void;
  onShowDatasetDetail?: () => void;
  onShowCollectionDetail?: (id: string, name: string) => void;
  onFileType: any;
}

function DatasetDetailTree({
  dataLoading,
  onRenameClicked,
  onRewareHousingClicked,
  onDeleteClicked,
  onCreateCicked,
  onCloseCicked,
  onShowDatasetDetail,
  onShowCollectionDetail,
  onFileType,
}: Props) {
  const modal = useModal('timeModal', 'updateModal');
  const { isAdmin, isPermit } = usePermission();
  const { username, groupId } = useUserInfo();
  const isRoot = username == 'root';
  const {
    selectedTreeNode,
    selectedTreeKeys,
    setCurrentEditTreeData,
    setIsDelete,
    isHighlight,
    setUsers,
    users,
  } = useContextSelector(DatasetsContext, (s) => s);
  const { parentIdstore, getRolesList, rolesList, ungroupedId } = useDatasetStore();
  const { appId = '' } = useParams() as { appId: string };
  const router = useRouter();
  const { isPc } = useWindowWidth();
  const [isShowMoveToModal, setIsShowMoveToModal] = useState(false);
  const [title, setTitle] = useState<string>('新增知识库');
  const [forbidType, setForBidType] = useState('dataset');
  const [isShowModal, setIsShowModal] = useState(false); // 新增知识库的浮层
  const [showSetting, setShowSetting] = useState(false); // 展示高级设置
  const [showUsers, setShowUsers] = useState(false);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [tagesValue, setTagesValue] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [treeDataValue, setTreeDataValue] = useState('');
  const [treeDataValue1, setTreeDataValue1] = useState('');
  const [disabledData, setDisabledData] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [isFlag, setIsFlag] = useState('');
  const [managers, setManagers] = useState<any[]>([]); // 知识库管理员
  const [approves, setApproves] = useState<any[]>([]); // 知识库审批人
  const [createDataset, setCreateDataset] = useState<boolean>(false);
  const [optionsTages, setOptionsTages] = useState<any[]>([]); // 文档类型
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);
  const [messageApi, contextHolder] = message.useMessage();
  const [defaultValue, setDefaultValue] = useState([]);
  const [knowledgeType, setKnowledgeType] = useState<boolean>(true);
  const [updateNode, setUpdateNode] = useState(null);
  const [searchData, setSearchData] = useState('');
  const [renameType, setRenameType] = useState('');
  const [isDatasetModalVisible, setIsDatasetModalVisible] = useState(false);
  const [isUpdateChild, setIsUpdateChild] = useState(false);

  const [createKnowledgeBaseData, setCreateKnowledgeBaseData] = useState({
    parentId: parentIdstore == '' ? null : parentIdstore,
    app_id: appId,
    type: 'dataset',
    name: '',
    intro: '',
    avatar: '',
    openapiUrl: '',
    dataset_tags: [''],
    groupId,
    assessor: [],
    administrator: [],
    vectorModel: 'embedding-model',
    agentModel: 'vllm-chat-model',
  });

  const { userRole } = useOrchestrationStore();
  const isPermitAdmin = userRole !== UserRoleEnum.admin;

  useEffect(() => {
    // 获取选择知识库组列表
    // getSelectKnowledgeBaseList()
    // 获取文档类型
    getDocumentType();
    // 获取用户权限
    // getRoles();
  }, []);
  useEffect(() => {
    setRenameType(onFileType);
  }, [onFileType]);

  useEffect(() => {
    if (isShowModal) {
      handleOK();
    }
  }, [isUpdateChild]);

  const itemsMore: MenuProps['items'] = [
    {
      key: '2',
      label: '移动至...',
      onClick: () => {
        setCurrentEditTreeData(selectedTreeNode);
        setIsShowMoveToModal(true);
      },
    },
    ...(isRoot
      ? [
          {
            key: '1',
            label: '重新入库',
            onClick: () => {
              onRewareHousingClicked &&
                onRewareHousingClicked(selectedTreeNode?.id ?? '', selectedTreeNode?.type ?? '');
            },
          },
        ]
      : []),
    {
      key: '3',
      label: `删除${selectedTreeNode?.type == 'folder' ? '文件夹' : '知识库'}`,
      onClick: () => {
        onDeleteClicked &&
          onDeleteClicked(selectedTreeNode?.id ?? '', selectedTreeNode?.type ?? '');
      },
    },
  ];

  const createMenu: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg">
            <SvgIcon color="#FFCA28" className="m-1" icon="ri--folder-2-fill" size={20} />
          </div>
          <span>新建文件夹</span>
        </div>
      ),
      onClick: () => {
        if (!parentIdstore) {
          setTreeDataValue('');
        }
        setTreeDataValue1(groupId as string);
        setSearchValue('');
        setKnowledgeType(true);
        setIsShowModal(true);
        setTitle('新增文件夹');
        setForBidType('folder');
        getRoles();
        setTagesValue([]);
        // 更新
        setCreateKnowledgeBaseData((prev) => ({
          ...prev,
          parentId: parentIdstore == '' ? null : parentIdstore,
          groupId,
          type: 'folder',
          name: '',
          dataset_tags: [],
        }));
        // onCreateCicked && onCreateCicked('folder');
      },
    },
    {
      key: '2',
      label: (
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg">
            <SvgIcon color="#3F70FF" className="m-1" icon="mdi--folder-zip" size={20} />
          </div>
          <span>新建知识库</span>
        </div>
      ),
      onClick: () => {
        if (!parentIdstore) {
          setTreeDataValue('');
        }
        setTreeDataValue1(groupId as string);
        setSearchValue('');
        setKnowledgeType(true);
        setIsShowModal(true);
        setApproves([]);
        setManagers([]);
        setForBidType('dataset');
        setTitle('新增知识库');
        getRoles();
        setTagesValue([]);
        // 更新
        setCreateKnowledgeBaseData((prev) => ({
          ...prev,
          parentId: parentIdstore == '' ? null : parentIdstore,
          groupId,
          dataset_tags: [],
          type: 'dataset',
          name: '',
        }));
        // onCreateCicked && onCreateCicked('dataset');
      },
    },
  ];

  const importData = () => {
    if (!selectedTreeNode) {
      return;
    }
    const { type } = selectedTreeNode;
    const parent = getNodeParentType(selectedTreeNode.parent, 'dataset');
    const datasetid = type == 'dataset' ? selectedTreeNode.id || selectedTreeNode?._id : parent?.id;
    const name = type == 'dataset' ? selectedTreeNode.name : parent?.name;
    const url =
      selectedTreeNode.type == 'folder'
        ? `/know/datasets/detail?id=${datasetid}&name=${name}&parentId=${selectedTreeNode.id}`
        : `/know/datasets/detail?id=${datasetid}&name=${name}`;
    onShowDatasetDetail && onShowDatasetDetail();
    !onShowDatasetDetail && router.push(url);
  };

  const getMenus = () => {
    // 父级中没有知识库 文件夹 新建文件夹 新建知识库
    // 父级中有知识库 新建文件夹 导入文件
    // 知识库 新建文件夹 导入文件

    if (!selectedTreeNode) {
      return createMenu;
    }
    const { type } = selectedTreeNode;

    const parent = getNodeParentType(selectedTreeNode.parent, 'dataset');

    if (parent || type == 'dataset') {
      const datasetid = type == 'dataset' ? selectedTreeNode.id : parent?.id;
      const name = type == 'dataset' ? selectedTreeNode.name : parent?.name;
      const editType = type == 'dataset' ? 'datasetcollction' : 'folder';
      const menus: MenuProps['items'] = [
        // {
        //   key: '1',
        //   label: (
        //     <div className="flex items-center gap-2">
        //       <div
        //         className="flex h-8 w-8 items-center justify-center rounded-lg"
        //       >
        //         <SvgIcon color='#4e87ff' icon="ri--folder-2-fill" size={20} />
        //       </div>
        //       <span>新建文件夹</span>
        //     </div>
        //   ),
        //   onClick: () => {
        //     onCreateCicked && onCreateCicked(editType);
        //   },
        // },
        {
          key: '2',
          label: (
            <div className="flex items-center gap-2">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg">
                <SvgIcon color="#BF63FF" icon="ri--layout-horizontal-fill" size={20} />
              </div>
              <span>导入数据</span>
            </div>
          ),
          onClick: () => {
            const url =
              selectedTreeNode.type == 'folder'
                ? `/know/datasets/detail?id=${datasetid}&name=${name}&parentId=${selectedTreeNode.id}`
                : `/know/datasets/detail?id=${datasetid}&name=${name}`;
            router.push(url);
          },
        },
      ];
      return menus;
    }

    return createMenu;
  };

  const showMoveTo = () => {
    setIsShowMoveToModal(true);
  };

  // 知识库浮层确认方法
  const handleOK = async () => {
    if (!createKnowledgeBaseData.name) {
      message.error('名称不能为空');
      return;
    }
    if (createKnowledgeBaseData.name.length > MAX_NAME_LENGTH) {
      message.error(`名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    // if (
    //   (createKnowledgeBaseData.dataset_tags.length == 0 || tagesValue === undefined) &&
    //   forbidType === 'dataset'
    // ) {
    //   message.error('请选择文档类型');
    //   return;
    // }
    handleCancel(); // 关闭浮层
    console.log(createKnowledgeBaseData);
    console.log(parentIdstore);
    // 确定发送请求
    if (knowledgeType) {
      try {
        await datasetService.createKnowledgeBase(createKnowledgeBaseData);
        messageApi.success('新建成功');
        setCreateDataset(!createDataset);
      } catch (error) {
        console.log(error);
        messageApi.error('新建失败');
      }
    } else {
      try {
        await datasetService.updateKnowledgeBase(createKnowledgeBaseData);
        messageApi.success('修改成功');
        setCreateDataset(!createDataset);
      } catch (error) {
        console.log(error);
        messageApi.error('修改失败');
      }
    }
  };
  // 知识库浮层取消方法
  const handleCancel = () => {
    setIsShowModal(false);
  };
  const onPopupScroll: TreeSelectProps['onPopupScroll'] = (e) => {
    console.log('onPopupScroll', e);
  };
  const onChange = (newValue: string) => {
    setTreeDataValue1(newValue);
    setCreateKnowledgeBaseData({
      ...createKnowledgeBaseData,
      groupId: newValue,
    });
  };

  // 获取选择知识库列表
  const getSelectKnowledgeBaseList = async () => {
    try {
      const res = await datasetService.knowledgeBaseSelect({
        // id: treeDataValue || groupId,
        id: groupId,
      });
      const plainList = treeToPlainList(res);
      setUsers(plainList);
      setTreeData([processData(res)]);
    } catch (error) {
      message.error(error);
    }
  };

  // 获取文档类型
  const getDocumentType = async () => {
    const data = {
      page: 1,
      page_size: 10,
      offset: 0,
      searchText: '',
      isPage: false,
    };
    try {
      const res = await datasetService.documentTypeList(data);
      // res.forEach((item: any) => {
      //   item.label = item
      //   item.value = item
      // })
      const req = [];
      for (let i = 0; i < res.list.length; i++) {
        req.push({ label: res.list[i], value: res.list[i] });
      }
      setOptionsTages(req);
    } catch (error) {
      message.error(error);
    }
  };

  // 确定选择知识库
  const handleUserSelectConfirm = (users: any) => {
    setShowUsers(false);
    if (isFlag === 'manager') {
      setManagers(users); // 拿到了选中的知识库数据   (管理员)
      // 过滤出id
      changeManageApproves(users, 'manager');
    } else {
      setApproves(users); // 拿到了选中的知识库数据   (审批人)
      changeManageApproves(users, 'approve');
    }
    console.log(users, 'users');
  };
  // 取消选择知识库
  const handleUserSelectCancel = () => {
    setShowUsers(false);
  };
  // 打开选择知识库浮层
  const openUserSelect = (flag: string) => {
    setShowUsers(true);
    setIsFlag(flag);
    if (flag === 'approve') {
      setDefaultValue(approves);
    } else {
      setDefaultValue(managers);
    }
  };
  // 删除审核或管理员
  const deleteUser = (flag: string, id: string) => {
    let datas = [];
    if (flag === 'manager') {
      datas = managers.filter((item: any) => item.id !== id);
      setManagers(datas);
      changeManageApproves(datas, 'manager');
    } else {
      datas = approves.filter((item: any) => item.id !== id);
      setApproves(datas);
      changeManageApproves(datas, 'approve');
    }
  };
  // 统一处理管理员和审核员
  function changeManageApproves(data: any, type: string) {
    const safeData = Array.isArray(data) ? data : [];

    console.log('safeData======', safeData);

    if (type === 'manager') {
      setCreateKnowledgeBaseData((prev) => ({
        ...prev,
        administrator: safeData.map((item) => item.id),
      }));
    } else {
      setCreateKnowledgeBaseData((prev) => ({
        ...prev,
        assessor: safeData.map((item) => item.id),
      }));
    }
    setUpdateNode(null);
  }

  useEffect(() => {
    getSelectKnowledgeBaseList(); // 重新获取
  }, [treeDataValue]);

  const onUpdateClicked = async (node: TreeData) => {
    // 判断是知识库还是文件夹
    if (node.type === 'folder') {
      setForBidType('folder');
    } else {
      setForBidType('dataset');
    }

    setUpdateNode(node);
    // 调用管理员和审核员接口
    // 使用函数式  useEfffect
    setCreateKnowledgeBaseData((prev) => ({
      ...prev,
      groupId: node.groupId,
      dataset_tags: node.dataset_tags,
      name: node.name,
      type: node.type,
      dataset_id: node?.id || node?._id || null,
    }));

    await getRoles();

    setKnowledgeType(false);
    setIsShowModal(true);
    setTagesValue(node?.dataset_tags); // 清空搜索框
    setSearchValue(node?.name);
    setTreeDataValue(node.groupId);
    setTreeDataValue1(node.groupId);
    setTitle('编辑知识库');
  };

  async function getRoles() {
    const res = await getRolesList(appId);
    setDisabledData(res.filter((item: any) => item.code === 'admin')[0]?.target_users);
    res?.forEach((item) => {
      if (item.code === 'knowledge_manager') {
        setManagers(item?.target_users);
        changeManageApproves(item?.target_users, 'manager');
      }
      if (item.code === 'knowledge_reviewer') {
        setApproves(item?.target_users);
        changeManageApproves(item?.target_users, 'approve');
      }
    });
  }

  const onChangeType = (info: any, flag: boolean) => {
    setTreeDataValue(info.node.groupId);
    setTreeDataValue1(info.node.groupId);
  };

  const reNameFn = () => {
    getRoles();
    setCreateKnowledgeBaseData((prev) => ({
      ...prev,
      groupId: selectedTreeNode?.groupId,
      dataset_tags: selectedTreeNode?.dataset_tags,
      name: selectedTreeNode?.name,
      type: selectedTreeNode?.type,
      dataset_id: selectedTreeNode?.id || selectedTreeNode?._id || null,
    }));
    setIsDatasetModalVisible(true);
    setCurrentEditTreeData(selectedTreeNode);
    // onRenameClicked && onRenameClicked(selectedTreeNode?.name ?? '');
  };

  return (
    <div className="flex h-full flex-col overflow-hidden">
      {contextHolder}
      {/* {dataLoading && (
        <div>
          <DatasetDetailSkeleton />
        </div>
      )} */}

      {
        <div className="flex h-full w-full flex-col overflow-hidden">
          <BreadCrumb
            disable={false}
            onCloseCicked={onCloseCicked}
            onCloseSearch={() => {
              setSearchData('');
            }}
            reNameFn={reNameFn}
            onUpdateType={(item) => {
              setRenameType((prev) => ({ ...prev, type: item.type }));
            }}
          />
          <TipDesc title="创建、上传和管理知识库，支持多种格式的文档" className="ml-5" />
          <div ref={ref} className="mt-2 h-full w-full overflow-hidden rounded-xl bg-[#FFFFFF]">
            <div className="flex w-full items-center">
              <div className="ml-4 flex">
                {/* {selectedTreeNode?.type === 'folder' ? (
                  <SvgIcon color="#FFCA28" className="m-1" icon="ri--folder-2-fill" size={32} />
                ) : (
                  <SvgIcon color="#3F70FF" className="m-1" icon="mdi--folder-zip" size={32} />
                )} */}
                {/* <div className="ml-2 flex">
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Text
                      className=" truncate text-base font-bold"
                      ellipsis={{ tooltip: selectedTreeNode?.name }}
                    >
                      {selectedTreeNode
                        ? isPc
                          ? selectedTreeNode?.name
                          : `${selectedTreeNode?.name.substring(0, 8)}...`
                        : '知识库总览'}
                    </Text>
                    {isPermit && selectedTreeNode && (
                      <div
                        className="ml-1 cursor-pointer "
                        onClick={() => {
                          console.log(selectedTreeNode, createKnowledgeBaseData);
                          setCreateKnowledgeBaseData((prev) => ({
                            ...prev,
                            groupId: selectedTreeNode?.groupId,
                            dataset_tags: selectedTreeNode?.dataset_tags,
                            name: selectedTreeNode?.name,
                            type: selectedTreeNode?.type,
                            dataset_id: selectedTreeNode?.id || selectedTreeNode?._id || null,
                          }));
                          setIsDatasetModalVisible(true);
                          setCurrentEditTreeData(selectedTreeNode);
                          // onRenameClicked && onRenameClicked(selectedTreeNode?.name ?? '');
                        }}
                      >
                        <SvgIcon icon="ic_rj_pen" size="20" />
                      </div>
                    )}
                  </div>
                </div> */}
              </div>

              <div className="mb-4  ml-auto mt-2 flex w-full items-center self-center">
                {isPermit && (
                  <div className="flex w-full justify-between">
                    <Input
                      placeholder="请输入内容"
                      onChange={(e) => {
                        setSearchData(e.target.value);
                      }}
                      value={searchData}
                      suffix={<SvgIcon icon="work-ic6" size={16} />}
                      className=" !rounded-md"
                      style={{
                        height: '32px',
                        width: '240px',
                      }}
                    />

                    <div className="flex items-center">
                      <div className="mr-4 flex h-4 items-center">
                        {selectedTreeKeys.length > 0 && (
                          <>
                            <span className="text-[#1D2129]">
                              已选择{' '}
                              <span className="font-semibold">{selectedTreeKeys.length}</span> 项
                            </span>
                            {selectedTreeNode?.type == 'dataset' && (
                              <Button
                                type={isHighlight ? 'primary' : 'text'}
                                className={`ml-4 flex h-8
                                    ${isHighlight ? '!cursor-pointer' : '!cursor-not-allowed'}
                                            items-center rounded-md !border !border-line-2 !bg-fill-1 px-2 text-text-4`}
                                onClick={() => {
                                  if (isHighlight) {
                                    modal.timeModal.open();
                                  }
                                }}
                              >
                                <SvgIcon icon="message-ic25" className="mr-1" size={20} />
                                延长时间
                              </Button>
                            )}

                            <div
                              className={`ml-4 flex h-8
                                            cursor-pointer items-center rounded-md border border-@error-color-disabled bg-@error-color-light px-2 text-@error-color-hover`}
                              onClick={() => {
                                setIsDelete(true);
                              }}
                            >
                              <SvgIcon icon="message-ic3" className="mr-1" size={20} />
                              删除
                            </div>
                          </>
                        )}
                      </div>
                      {selectedTreeNode?.type === 'dataset' ? (
                        <div>
                          <Button
                            type="text"
                            className={`mr-6 rounded-sm
                              ${
                                selectedTreeNode.groupId !== ungroupedId &&
                                !getIsEditPermission(users, selectedTreeNode)
                                  ? '!cursor-not-allowed  !bg-bg-4 '
                                  : ''
                              }`}
                            icon={<SvgIcon icon="adddata" size={20} />}
                            onClick={() => {
                              if (
                                selectedTreeNode.groupId !== ungroupedId &&
                                !getIsEditPermission(users, selectedTreeNode)
                              ) {
                                return;
                              }
                              importData();
                            }}
                            style={{ border: '1px solid #1B6DFA' }}
                          >
                            导入数据
                          </Button>
                        </div>
                      ) : (
                        (isAdmin ||
                          selectedTreeNode ||
                          userRole != UserRoleEnum.knowledge_reviewer) && (
                          <div>
                            <Dropdown
                              trigger={isPc ? ['hover'] : ['click']}
                              className={`rounded-sm ${isPc ? 'mr-6' : 'mr-2'}`}
                              menu={{ items: getMenus() }}
                              placement="bottomLeft"
                              arrow
                            >
                              <Button
                                className={`rounded-sm ${isPc ? 'mr-10' : 'mr-2'}`}
                                type="text"
                                icon={<PlusOutlined />}
                                style={{ border: '1px solid #1B6DFA' }}
                              >
                                新建
                              </Button>
                            </Dropdown>
                          </div>
                        )
                      )}
                    </div>
                  </div>
                )}

                {/* {isAdmin && selectedTreeNode && (
                  <Dropdown
                    trigger={isPc ? ['hover'] : ['click']}
                    className="mr-2"
                    menu={{ items: itemsMore }}
                    placement="bottomLeft"
                  >
                    <Button type="text" className="mr-2" icon={<EllipsisOutlined />} />
                  </Dropdown>
                )} */}
              </div>
            </div>

            <DatasetsTreeList
              dataLoading={dataLoading}
              createDataset={createDataset}
              onRewareHousingClicked={onRewareHousingClicked}
              parentSize={size ?? { height: 0, width: 0 }}
              onDeleteClicked={onDeleteClicked}
              onRenameClicked={onRenameClicked}
              onUpdateClicked={onUpdateClicked}
              showMoveTo={showMoveTo}
              onShowCollectionDetail={onShowCollectionDetail}
              onChangeType={onChangeType}
              searchData={searchData}
              onRenameType={renameType}
            />
          </div>

          <MoveToModal
            visible={isShowMoveToModal}
            onCancel={() => setIsShowMoveToModal(false)}
            appId={appId}
          />

          {/* 新增或修改知识库 */}
          <Modals
            title={title}
            width={860}
            centered
            open={isShowModal}
            onOk={() => {
              if (knowledgeType) {
                handleOK();
              } else {
                modal.updateModal.open();
              }
            }}
            onCancel={handleCancel}
          >
            <div className="text-sm text-[#474C5F]">
              {forbidType === 'dataset' ? '知识库名称' : '文件夹名称'}
            </div>
            <Input
              onChange={(e) => {
                // const limitedValue = limitTextLength(e.target.value, MAX_NAME_LENGTH);
                setSearchValue(e.target.value);
                setCreateKnowledgeBaseData({ ...createKnowledgeBaseData, name: e.target.value });
              }}
              value={searchValue}
              className="!my-[10px] h-[40px] !rounded-default !bg-[#F8F8F8]"
              style={{
                border: 'none',
              }}
              placeholder={forbidType === 'dataset' ? '请输入知识库名称' : '请输入文件夹名称'}
            />
            {forbidType === 'dataset' && (
              <div>
                <div className="text-xs text-[#474C5F]">文档类型</div>
                <Select
                  placeholder="默认"
                  mode="tags"
                  value={tagesValue}
                  className="select-knowledge"
                  style={{ width: '100%' }}
                  onChange={(users) => {
                    if (optionsTages && optionsTages.length > 0) {
                      const validUsers = users.filter((user) => {
                        return optionsTages.some(
                          (option) => option.value === user || option.label === user,
                        );
                      });
                      if (validUsers.length !== users.length) {
                        console.warn('部分标签无效，未被添加');
                      }
                      setTagesValue([...validUsers]);
                      setCreateKnowledgeBaseData({
                        ...createKnowledgeBaseData,
                        dataset_tags: validUsers,
                      });
                    }
                  }}
                  tokenSeparators={optionsTages?.length > 0 ? [','] : []} // 动态设置分隔符
                  options={optionsTages}
                  notFoundContent={optionsTages?.length === 0 ? '无可用标签，无法添加' : undefined}
                  onInputKeyDown={(e) => {
                    // 当没有选项数据时，阻止回车键添加标签
                    if (optionsTages?.length === 0) {
                      e.preventDefault();
                    }
                  }}
                  filterOption={(input, option) => {
                    return option?.label?.toLowerCase().includes(input.toLowerCase());
                  }}
                />
              </div>
            )}
            <div className="mb-2 text-xs text-[#474C5F]">归属组织</div>
            <TreeSelect
              showSearch
              value={treeDataValue1 || groupId}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeDefaultExpandAll
              onChange={onChange}
              treeData={treeData}
              onPopupScroll={onPopupScroll}
              className="select-org"
              filterTreeNode={(inputValue, treeNode) => {
                // 支持中文、拼音和路径匹配
                const title = treeNode.title?.toLowerCase();
                const input = inputValue.toLowerCase();
                // 匹配路径（父节点+当前节点）
                const parentTitle = treeNode.parentNode?.title?.toLowerCase() || '';
                if (`${parentTitle} ${title}`.includes(input)) {
                  return true;
                }
                return false;
              }}
            />
            {forbidType === 'dataset' && !isPermitAdmin && (
              <div>
                <div className="text-sm text-gray-400">
                  注：仅该组织的管理人员可见此知识库，默认开启此组织的问答权限。
                </div>
                <div
                  className=" mt-4 flex cursor-pointer items-center text-[12px] text-@brand-color"
                  onClick={() => setShowSetting(!showSetting)}
                >
                  {showSetting ? (
                    <CaretDownOutlined color="#4F74FF" style={{ fontSize: '16px' }} />
                  ) : (
                    <CaretRightOutlined color="#4F74FF" style={{ fontSize: '16px' }} />
                  )}
                  高级设置
                </div>
              </div>
            )}
            {showSetting && forbidType === 'dataset' && (
              <div>
                <div className="mt-4">
                  <div className="flex items-center ">
                    <p className="text-[14px]">知识库管理员</p>
                    <p
                      className="ml-3 h-[22px] w-[44px] cursor-pointer rounded-xl bg-@brand-color text-center leading-[22px] text-[white]"
                      onClick={() => openUserSelect('manager')}
                    >
                      新增
                    </p>
                  </div>
                  <div className="my-2 text-sm text-gray-400">
                    可管理该知识库文档、知识治理、与应用进行问答
                  </div>

                  <div
                    style={
                      managers.length !== 0
                        ? { height: 'auto' }
                        : { height: '86px', lineHeight: '86px' }
                    }
                    className="bg-[#F8F8F8] text-center   text-gray-400 "
                  >
                    {managers.length == 0 ? (
                      '暂无管理员'
                    ) : (
                      <div>
                        <div className="flex h-[40px] w-full items-center justify-between text-[12px] text-[#868686] ">
                          <div className="w-[100px]">组织</div>
                          <div className="w-[100px]">学号</div>
                          <div className="w-[100px]">用户名</div>
                          <div className="w-[100px]">操作</div>
                        </div>
                        <List
                          // style={{ height: "260px", overflow: 'auto', }}
                          className="modules-list"
                          dataSource={managers}
                          renderItem={(item) => (
                            <List.Item className="p-2 hover:bg-[#F5F7FA]">
                              <div className="flex w-full items-center justify-between">
                                <span className="w-[100px]">{item.group.name}</span>
                                <span className="w-[100px]">{item.user_id}</span>
                                <span className="w-[100px]">{item.name}</span>
                                <span
                                  className="w-[100px] cursor-pointer text-[#FF4040]"
                                  onClick={() => {
                                    deleteUser('manager', item.id);
                                  }}
                                >
                                  删除
                                </span>
                              </div>
                            </List.Item>
                          )}
                        />
                      </div>
                    )}
                  </div>
                </div>
                <div className="mt-4">
                  <div className="flex items-center ">
                    <p className="text-[14px]">知识库审批员</p>
                    <p
                      className="ml-3 h-[22px] w-[44px] cursor-pointer rounded-xl bg-@brand-color text-center leading-[22px] text-[white]"
                      onClick={() => openUserSelect('approve')}
                    >
                      新增
                    </p>
                  </div>
                  <div className="my-2 text-sm text-gray-400">
                    可审核新增知识库内容是否合规、与应用进行问答
                  </div>
                  <div
                    style={
                      approves.length !== 0
                        ? { height: 'auto' }
                        : { height: '86px', lineHeight: '86px' }
                    }
                    className="bg-[#F8F8F8] text-center  text-gray-400"
                  >
                    {approves.length == 0 ? (
                      '暂无管理员'
                    ) : (
                      <div>
                        <div className="flex h-[40px] w-full items-center justify-between text-[12px] text-[#868686] ">
                          <div className="w-[100px]">组织</div>
                          <div className="w-[100px]">学号</div>
                          <div className="w-[100px]">用户名</div>
                          <div className="w-[100px]">操作</div>
                        </div>
                        <List
                          // style={{ height: "260px", overflow: 'auto', }}
                          className="modules-list"
                          dataSource={approves}
                          renderItem={(item) => (
                            <List.Item className="p-2 hover:bg-[#F5F7FA]">
                              <div className="flex w-full items-center justify-between">
                                <span className="w-[100px]">{item.group.name}</span>
                                <span className="w-[100px]">{item.user_id}</span>
                                <span className="w-[100px]">{item.name}</span>
                                <span
                                  className="w-[100px] cursor-pointer text-[#FF4040]"
                                  onClick={() => deleteUser('approve', item.id)}
                                >
                                  删除
                                </span>
                              </div>
                            </List.Item>
                          )}
                        />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </Modals>

          {/* <UserSelectModal
            visible={showUsers}
            dataSource={users}
            selectedIds={selectedIds}
            onCancel={handleUserSelectCancel}
            onConfirm={handleUserSelectConfirm}
            confirmText="确定"
            cancelText="取消"
            title="选择知识库管理员"
          /> */}

          <PersonnelModal
            title="选择知识库管理员"
            destroyOnClose
            defaultValue={defaultValue}
            appId={appId}
            onSubmit={handleUserSelectConfirm}
            open={showUsers}
            onCancel={handleUserSelectCancel}
            isCheckBox={false}
            disabled={disabledData}
          />

          <UpdateNameModal
            isDatasetModalVisible={isDatasetModalVisible}
            setIsDatasetModalVisible={setIsDatasetModalVisible}
            updateNode={createKnowledgeBaseData}
          />
          <OvertimeModal
            open={modal.timeModal.isOpen}
            onCancel={() => modal.timeModal.close()}
            onOk={() => {
              setCreateDataset(!createDataset);
            }}
          />
          <UpdateDatasetModal
            isOpen={modal.updateModal.isOpen}
            onCancel={() => {
              modal.updateModal.close();
              setIsUpdateChild(!isUpdateChild);
              setCreateKnowledgeBaseData((prev) => ({
                ...prev,
                isUpdateChild: false,
              }));
            }}
            onOk={() => {
              modal.updateModal.close();
              setIsUpdateChild(!isUpdateChild);
              setCreateKnowledgeBaseData((prev) => ({
                ...prev,
                isUpdateChild: true,
              }));
            }}
          />
        </div>
      }
    </div>
  );
}

export default memo(DatasetDetailTree);
